import Vue from 'vue';
import { ref } from '@vue/composition-api'
import staticConst from "@/js/const/StaticConst.js";
import https from "@/js/https/Https.js";
import config from "@/js/conf/Config.js";
import downloadFile from "@/js/upload/DownloadFile.js";
import ExcelExporter from '@/utils/excelExport.js'

const PAGE_SIZE = 1
// 创建一个单例状态
const state = {

    reqQuery: ref({
        in_out: 2, //非必须 出入库类型 1入库 2出库 默认2
        storeid: '', //非必须 仓库筛选 默认所有
        group: '', //非必须 报表类型 1 日报 2月报 3季报  5 自定义时间的日报 默认按日统计
        stime: "", //非必须 自定义时间统计 开始时间 格式"2020-01-28"
        dtime: "", //分页参数  默认为1 该参数仅为日报时候使用， 其他条件不参与分页
        page: 1, //分页参数  默认为1 该参数仅为日报时候使用， 其他条件不参与分页
        timestr: '',
    }),
    downTime: ref({
        stime: '',
        dtime: '',
    }),
    // 一级页面数据
    is_soll: ref(true),
    saleFlowsList: ref([]),
    count_ls: ref([]),
    loading: ref(false),
    hasMore: ref(true),
    store_ls: ref([]),
    staff_ls: ref([]),
    group_ls: ref([
        {
            id: '',
            name: "全部日期"
        },
        {
            id: 1,
            name: "日报"
        },
        {
            id: 2,
            name: "月报"
        },
        {
            id: 3,
            name: "季报"
        },
        {
            id: 5,
            name: "自定义",
            stime: true,
            dtime: true
        }
    ]),

    // 日数据弹窗
    fromTypes: ref(''),

    dateArray: ref([]),
    shopQuery: ref({
        stime: '',
        dtime: '',
        pfrom: 0,
        pnum: 20,
    }),
    shopList: ref([]),
    hasMoreShopSell: ref(true),
    shopsListLoading: ref(false),
    shopBgActiveId: ref(''),

    shopClickInfo: ref({}),
    shopListPfrom: ref(0),
    shopDetailList: ref([]),
    shopDetailInfo: ref({}),
    shopDetailLoading: ref(false),
    shopDetailHasMore: ref(true),
}

export const useBoundState = () => {

    const resetState = () => {
        state.count_ls.value = []
        state.hasMore.value = true // 恢复为 true，因为其他地方可能需要
        state.loading.value = false
        // 只在必要时重置 page，避免在已经设置 page 的情况下重复设置
        if (state.reqQuery.value.page !== 1) {
            state.reqQuery.value.page = 1
        }
    }

    const loadReportShopConut = () => {
        let param = state.reqQuery.value;
        state.loading.value = true
        // 如果是第一页，先重置数据（但不重置 page，因为已经设置过了）
        if (param.page === 1) {
            state.count_ls.value = []
            state.hasMore.value = true
        }
        https.getReportStoreInOut(param, back);
        function back(data) {
            state.loading.value = false
            if (!data) {
                return;
            }
            if (data.status == 1) {
                if (!data.data) {
                    return;
                }
                data = data.data;
                const newData = data || []
                const existingTimestrs = new Set(state.count_ls.value.map(item => item.timestr))
                const uniqueNewData = newData.filter(item => !existingTimestrs.has(item.timestr))
                state.count_ls.value = state.count_ls.value.concat(uniqueNewData)
                state.hasMore.value = (data && data?.length) >= PAGE_SIZE
            }
        }
    }

    const loadMoreData = () => {
        // 更严格的检查条件
        if (state.loading.value || !state.hasMore.value || state.count_ls.value.length === 0) {
            return
        }
        state.reqQuery.value.page += 1
        if (!state.reqQuery.value.stime) {
            loadReportShopConut()
        }
    }

    // 选择筛选
    const selectHandleChange = (value) => {
        if (state.loading.value) return;
        state.reqQuery.value.page = 1
        state.count_ls.value = []
        loadReportShopConut()
    }

    // 选择日期
    const selectDate = (value) => {
        // if (value == state.reqQuery.value.group) {
        //     return
        // }

        // 先设置 loading 为 true，hasMore 为 false，防止表格触发 loadMoreData
        state.loading.value = true
        state.hasMore.value = false

        state.reqQuery.value.group = value
        state.reqQuery.value.page = 1
        state.count_ls.value = []

        state.shopList.value = []
        state.shopQuery.value.pfrom = 0
        state.shopQuery.value.pnum = 20

        if (state.reqQuery.value.group != 5) {
            state.reqQuery.value.stime = ''
            state.reqQuery.value.dtime = ''
            state.dateArray.value = []
        }
        loadReportShopConut()
    }

    const loadReportStoreInOutGdLs = () => {
        state.shopsListLoading.value = true
        let param = {
            ...state.reqQuery.value,
            ...state.shopQuery.value
        };
        https.getReportStoreInOutGdLs(param, back);
        function back(data) {
            if (!data) {
                return;
            }
            if (data.status == 1) {
                data = data?.data;
                state.shopList.value = state.shopList.value.concat(data || [])
                state.hasMoreShopSell.value = (data && data?.length) >= PAGE_SIZE
            }
            state.shopsListLoading.value = false
        }
    }

    const shopListLoadMoreData = () => {
        if (state.shopsListLoading.value || !state.hasMoreShopSell.value) {
            return
        }
        state.shopQuery.value.pfrom += 20
        loadReportStoreInOutGdLs()
    }

    // 获取商品详情列表
    const getShopDetailList = async () => {
        let param = {
            ...state.reqQuery.value,
            ...state.shopQuery.value,
            pfrom: state.shopListPfrom.value,
            gdid: state.shopClickInfo.value.gdid,
            timestr: state.shopClickInfo.value.timestr
        };
        state.shopDetailLoading.value = true
        let res = await Vue.prototype.$api({ url: config.REPORT_STORE_IN_OUT_DETAIL, data: param });
        if (res.status == 1) {
            state.shopDetailList.value = state.shopDetailList.value.concat(res.data.list)
            state.shopDetailHasMore.value = (res.data.list && res.data.list?.length) >= PAGE_SIZE
            state.shopDetailInfo.value = res.data.info
        }
        state.shopDetailLoading.value = false
    }

    const shopDetailLoadMoreData = () => {
        if (state.shopDetailLoading.value || !state.shopDetailHasMore.value) {
            return
        }
        state.shopListPfrom.value += 20
        getShopDetailList()
    }

    /*****获取仓库列表******/
    const getReportStore = () => {
        https.getReportStoreCount({}, back);
        function back(data) {
            if (!data) return;
            if (data.status == 1) {
                if (!data.data) return;
                state.store_ls.value = data.data;
                state.store_ls.value = state.store_ls.value.map(item => {
                    return {
                        value: item.store_id,
                        label: item.store_name
                    }
                })
                state.reqQuery.value.storeid = state.store_ls.value?.[1]?.id || 0;
            }
        }
    }

    // 返回上级
    const goBack = () => {
        state.warehouse_showBack.value = false
        state.warehouse_clickItem.value = {}
    }

    // 导出数据表格
    const exportReport = async (type) => {
        let param = {
            ...state.reqQuery.value,
            ...state.downTime.value,
            pfrom: 0,
            pnum: 20,
        }
        let res = await Vue.prototype.$api({ url: config.report_store_in_out_goods_export, data: param });
        if (res.status == 1) {
            if (res.data.ls && res.data.ls.length > 0) {
                downloadExcel(res.data)
            } else {
                Vue.prototype.$message.error('导出失败：没有数据')
            }
        }
    }

    // 自定义表头映射
    const downloadExcel = async (data) => {
        // 根据 title 表头循环，从 list 数组对象中取值，生成新的 list
        let newList = data.ls.map(item => {
            let newItem = {}
            // 循环 title 对象的每个键
            for (let key in data.title) {
                // 如果 list 中的 item 包含这个字段，则提取其值
                if (item.hasOwnProperty(key)) {
                    newItem[key] = item[key]
                } else {
                    // 如果没有这个字段，设置为空字符串或默认值
                    newItem[key] = ''
                }
            }
            return newItem
        })
        try {
            const success = await ExcelExporter.export(
                newList, // 数据
                `${data.sheet_title}.xlsx`,
                data.title // 表头
            )
            if (success) {
                Vue.prototype.$message.success('成功导出表格,请保存')
            }
        } catch (error) {
            Vue.$message.error('导出失败：' + error?.message)
        }
    }

    return {
        ...state,
        loadReportShopConut,
        selectHandleChange,
        selectDate,
        loadMoreData,
        resetState,
        goBack,
        getReportStore,
        loadReportStoreInOutGdLs,
        shopListLoadMoreData,
        getShopDetailList,
        shopDetailLoadMoreData,
        exportReport
    }
} 